<template>
  <div :class="['btn', { isPosition: type == 0 }]">
    <div v-show="item.count > 0" @click="reduce(item)">-</div>
    <p class="shu" v-show="item.count > 0">{{ item.count }}</p>
    <div @click="add(item)">+</div>
  </div>
</template>

<script>
import { mapState , mapGetters } from 'vuex'
export default {
  props: ['item', 'type'],
  mounted(){
    // console.log(this.carList)
  },
  computed: {
    ...mapState(['carList']),
    ...mapGetters(['cartList'])
  },
  methods: {
    add(food) {
      if (!food.count) {
        food.count = 1
      } else {
        food.count++
      }
      this.$store.commit('setCarList', {
        item: food,
      })
      // console.log(this.carList)
    },
    reduce(food) {
      food.count--
      console.log(this.cartList)
      let index = -1 ;
      if( this.carList.length !== 0 ){
        index = this.carList.findIndex(( item )=>{
          return item.name === food.name ;
        });
      }
      console.log(index);
      if( index !== -1 && food.count < 1 ){
        food.count = 0 ;
        this.carList.splice( index , 1 );
      }
    },
  },
}
</script>

<style scoped>
.btn {
  display: flex;
  position: absolute;
  right: 0px;
  top: 6px;
}
.btn > div {
  width: 20px;
  height: 20px;
  border: 2px solid rgb(0, 160, 220);
  text-align: center;
  line-height: 12px;
  font-size: 24px;
  font-weight: bold;
  margin-top: 6px;
  border-radius: 50%;
}
.btn > div:first-child {
  color: blue;
}
.btn > div:last-child {
  color: #fff;
  background-color: rgb(0, 160, 220);
}
.shu {
  width: 22px;
  text-align: center;
  font-size: 10px;
  line-height: 24px;
}
/* .isPosition{
    position: absolute;
    right: 0;
    top: 0;
} */
</style>
